<?php
namespace app\admin\controller;

use think\Loader;
use think\Db;
use app\common\tools\jsonRPCClient;

/**
* 用户管理
* @author aierui github  https://github.com/Aierui
* @version 1.0 
*/
class Otc extends Admin
{

	function _initialize()
    {
        parent::_initialize();
    }


    //商城
    public function index(){
    	$info = Db::name('otc_sell')->where('available_num > 0')->select();
    	$this->assign('eth',$info);
        return view();
    }
    public function getList()
    {
        if(!request()->isAjax()) {
            $this->error(lang('Request type error'), 4001);
        }
        $request = request()->param();
        unset($request['/admin/otc/getlist']);
        
       
        $request = $this->fmtRequest($request);
		//$data = Db::name('otc_sell')->order('id asc')->where('available_num >0')->where( $request['map'] )->limit($request['offset'], $request['limit'])->select();
		$data = Db::name('otc_sell')->order('id asc')->where('available_num >0')->where( $request['map'] )->select();
		//$data = $this->_fmtData( $data );

        return $data;
    }

    public function sell()
    {

    	return view();
    }

    public function buy()
    {
    	if($this->request->isGet()){
            $data = $this->request->get();
            $id = "";
            if(isset($data['id']))
            {
                $id = $data['id'];
            }
            
            $sell = Db::name('otc_sell')->where('id',$id)->find();

            $this->assign('sell',$sell);
            
        }
    	if($this->request->isPost()){
            $data = $this->request->post();
            $sell = Db::name('otc_sell')->where('id',$data['id'])->find();
            if($data['buy_num']<=0)
            {
            	$this->error(info(lang('Please input the correct number'),0)['msg']);
            }
            if($sell['available_num'] < $data['buy_num'])
            {
            	$this->error(info(lang('The data entered must not be larger than the data that can be sold'),0)['msg']);
            }

            if($data['buy_num']%100 != 0)
            {
            	$this->error(info(lang('Please enter integer multiple of 100.'),0)['msg']);
            }

            Db::name('otc_sell')->where('id',$data['id'])->setDec('available_num',$data['buy_num']);

            //
            $admin = session('admin')['userinfo'];
        	$info = Db::name('user')->where('id',$admin['id'])->find();

        	$list['sell_eth']=$sell['eth'];
        	$list['sell_id']=$sell['id'];
        	$list['buy_eth'] = $info['eth'];
        	$list['buy_num'] =$data['buy_num'];
        	$ret = Db::name('otc_buy_list')->insertGetId($list);

        	$this->success(info(lang('The order is successful, please complete payment in time'),2,url('admin/otc/payment'))['msg'],'/admin/otc/payment?id='.$ret); 

        	

        }
    	return view();
    }

    public function create()
    {
    	$admin = session('admin')['userinfo'];
        $info = Db::name('user')->where('id',$admin['id'])->find();
    	if($this->request->isPost()){
            $data = $this->request->post();
            if($data['sell_num']<=0)
            {
            	$this->error(info(lang('Please input the correct number'),0)['msg']);
            }


            if($data['sell_num']%500 != 0)
            {
            	$this->error(info(lang('Please enter integer multiple of 500.'),0)['msg']);
            }

            $sum_sell = $data['sell_num'] ;
            if($sum_sell > $info['transaction'])
            {
            	$this->error(info(lang('The transaction value is not enough, and the transaction value is').$sum_sell,0)['msg']);
            }

            Db::name('user')->where('id',$admin['id'])->setDec('transaction',$sum_sell);

            //插入卖出信息
            $sell['eth'] = $info['eth'];
            $sell['sell_num'] = $data['sell_num']*0.8;
            $sell['available_num'] = $data['sell_num']*0.8;
            Db::name('otc_sell')->insert($sell);
            $this->success(info(lang('Release success'),0)['msg'],'/admin/otc/selllist');

        }

        $this->assign('info',$info);
    	return view();
    }

    public function buylist()
    {
    	$admin = session('admin')['userinfo'];
        $info = Db::name('user')->where('id',$admin['id'])->find();

        $list = Db::name('otc_buy_list')->where('buy_eth',$info['eth'])->where('status <> 2')->select();

        $this->assign('list',$list);
    	return view();
    }

    public function getstatus($state)
    {

    }

    public function getbuylist()
    {
    	if(!request()->isAjax()) {
            $this->error(lang('Request type error'), 4001);
        }
        $request = request()->param();
        unset($request['/admin/otc/getbuylist']);
        
       	$admin = session('admin')['userinfo'];
        $info = Db::name('user')->where('id',$admin['id'])->find();

        $request = $this->fmtRequest($request);
		$data = Db::name('otc_buy_list')->order('id asc')->where('buy_eth',$info['eth'])->where('status<2')->where( $request['map'] )->select();

		
		//$data = $this->_fmtData( $data );
		$data = $this->fmtBuylistData( $data );

		//$data['total'] = 100;
        return $data;
    	
    }

    public function payment()
    {
    	$id = "";
    	if($this->request->isGet()){
            $data = $this->request->get();
            
            if(isset($data['id']))
            {
                $id = $data['id'];
            }
            

            
        }

        if($this->request->isPost()){
        	$file = $this->request->file('file_input');

        	$data = $this->request->post();
        	

        	//对文件进行验证，判断是否是图片文件
        	if(!$file)
        	{
        		$this->error(info(lang('Submit failure'),0)['msg']);
        	}

        	$id = $data['id'];

        	
        	$path = ROOT_PATH . 'public/tmp/uploads/';

        	$info = $file->move($path);
        	if (!$info) 
        	{
            	return ajax_return_error($file->getError());
        	}
        	$img = $this->request->root() . '/tmp/uploads/' . $info->getSaveName();
        	Db::name('otc_img')->where('buy_id',$id)->delete();

        	$img_data['buy_id'] = $id;
        	$img_data['img_src'] = $img;
        	Db::name('otc_img')->insert($img_data);
        	$status['status'] = 1;
            Db::name('otc_buy_list')->where('id',$id)->update($status);
            $this->success(info(lang('Submit success'),0)['msg']);

        }
        if(!$id)
        {
        	$this->redirect("/admin/otc/buylist");
        }

        $sell = Db::name('otc_buy_list')->where('id',$id)->find();

        $user = Db::name('user')->where('eth',$sell['sell_eth'])->find();


        $account = Db::name('account')->where('uid',$user['id'])->find();
        $img = Db::name('otc_img')->where('buy_id',$id)->find();

        $img_src = "";
        if($img)
        {
            $img_src = $img['img_src'];
        }
        $state ="";
        if($sell['status']==0)
        {
            $state =lang('Buyer not paid');
        }
        if($sell['status']==1)
        {
            $state =lang('Waiting for seller confirmation');
        }

            
        $this->assign('state',$state);
        $this->assign('img_src',$img_src);
        $this->assign('sell',$sell);
        $this->assign('user',$user);
        $this->assign('account',$account);
        
        return view();
    }

    public function selllist()
    {
    	$admin = session('admin')['userinfo'];
        $info = Db::name('user')->where('id',$admin['id'])->find();

       

        
    	return view();
    	
    }



    public function getselllist()
    {
    	if(!request()->isAjax()) {
            $this->error(lang('Request type error'), 4001);
        }
        $request = request()->param();
        unset($request['/admin/otc/getselllist']);
        
       
        $request = $this->fmtRequest($request);
		$data = Db::name('otc_sell')->order('id asc')->where('status = 0')->where( $request['map'] )->select();
		
		//$data = $this->fmtBuylistData( $data );

        return $data;
    }

    public function sublist()
    {
    	$id = "";
    	if($this->request->isGet()){
            $data = $this->request->get();
            
            if(isset($data['id']))
            {
                $id = $data['id'];
            }

        }
        if($id=="")
        {
        	$this->redirect("/admin/otc/selllist");
        }
        $this->assign('id',$id);
    	return view();
    }

    public function getsublist()
    {
    	if(!request()->isAjax()) {
            $this->error(lang('Request type error'), 4001);
        }

        $id = "";
    	if($this->request->isGet()){
            $data = $this->request->get();
            
            if(isset($data['id']))
            {
                $id = $data['id'];
            }

        }
        $params = input('param.');

        $id = $params['id'];
        $request = request()->param();
        unset($request['/admin/otc/getsublist']);
        
       	$admin = session('admin')['userinfo'];
        $info = Db::name('user')->where('id',$admin['id'])->find();

        $request = $this->fmtRequest($request);
		$data = Db::name('otc_buy_list')->order('id asc')->where('sell_id',$id)->where('sell_eth',$info['eth'])->select();

		
		//$data = $this->_fmtData( $data );
		$data = $this->fmtBuylistData( $data );

		//$data['total'] = 100;
        return $data;

    }

    

    public function receive()
    {

    	$id = "";
    	if($this->request->isGet()){
            $data = $this->request->get();
            
            if(isset($data['id']))
            {
                $id = $data['id'];
            }

            if($id=="")
	        {
	        	$this->redirect("/admin/otc/selllist");
	        }
        }

        
        $admin = session('admin')['userinfo'];
        $info = Db::name('user')->where('id',$admin['id'])->find();


        if($this->request->isPost())
        {
        	$file = $this->request->file('file_input');

        	$data = $this->request->post();
        	$id = $data['id'];

        	if($id=="")
	        {
	        	$this->redirect("/admin/otc/selllist");
	        }

        	if(!$id)
        	{
        		$this->redirect("/admin/otc/selllist");
        	}
            $sell = Db::name('otc_buy_list')->where('id',$id)->where('sell_eth',$info['eth'])->find();

            if(!$sell)
            {
            	$this->redirect("/admin/otc/selllist");
            }
            $status['status'] = 2;
            Db::name('otc_buy_list')->where('id',$id)->update($status);
            //更新购买人的记录
            Db::name('user')->where('eth',$sell['buy_eth'])->setInc('transaction',$sell['buy_num']*0.8);
            Db::name('user')->where('eth',$sell['buy_eth'])->setInc('source',$sell['buy_num']*0.2);

            $tra_otc['eth']=$sell['buy_eth'];
            $tra_otc['transaction']=$sell['buy_num']*0.8;
            $tra_otc['source']=$sell['buy_num']*0.2;
            
            $this->success(info(lang('Submit success'),0)['msg']);
        }
		$sell = Db::name('otc_buy_list')->where('id',$id)->where('sell_eth',$info['eth'])->find();
        $user = Db::name('user')->where('eth',$sell['buy_eth'])->find();


        $account = Db::name('account')->where('uid',$user['id'])->find();
        $img = Db::name('otc_img')->where('buy_id',$id)->find();
            
            
        $img_src = "";
        if($img)
        {
            	$img_src = $img['img_src'];
        }
        $state ="";
        if($sell['status']==0)
        {
            $state =lang('Buyer not paid');
        }
        if($sell['status']==1)
        {
            $state =lang('Waiting for seller confirmation');
        }
        if($sell['status']==2)
        {
            $state =lang('Transaction completion');
        }
        
            //$this->success(info(lang('Submit success'),0)['msg']);
            
        $this->assign('state',$state);
        $this->assign('img_src',$img_src);
        $this->assign('sell',$sell);
        $this->assign('user',$user);
        $this->assign('account',$account);
        
        return view();
    }

	protected function fmtRequest( $request = [] )
    {
        if( empty($request) ) {
            return $request;
        }
        $offset = 0;
        if (isset($request['offset']) && is_numeric($request['offset']) ) {
            $offset = $request['offset'];
            unset($request['offset']);
        }
        $limit = 5;
        if (isset($request['limit']) && is_numeric($request['limit']) ) {
            $limit = $request['limit'];
            unset($request['limit']);
        }
        $ret = [
            'offset'=>$offset,
            'limit'=>$limit,
            'map'=>$request
        ];
        return $ret;
    }


    //格式化数据
	private function fmtBuylistData( $data )
	{
		if(empty($data) && is_array($data)) {
			return $data;
		}

		foreach ($data as $key => $value) {
			

			if($data[$key]['status']==0)
			{
				$data[$key]['status']=lang('Buyer not paid');
				
			}
			if($data[$key]['status']==1)
			{
				$data[$key]['status']=lang('Waiting for seller confirmation');
			}
			if($data[$key]['status']==2)
			{
				$data[$key]['status']=lang('Transaction completion');
			}

		}
		
		return $data;
	}


    
}